package com.example.demo.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import io.github.classgraph.json.Id;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.text.similarity.CosineSimilarity;
import org.apache.commons.text.similarity.JaccardSimilarity;
import org.apache.commons.text.similarity.LevenshteinDistance;
import org.apache.commons.text.similarity.CosineDistance;
import com.example.demo.entity.*;
import com.example.demo.mapper.*;
import com.example.demo.service.*;
import com.example.demo.utils.Result;
import com.google.gson.Gson;
import org.apache.poi.ss.formula.functions.Na;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.*;
import java.sql.SQLOutput;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;

import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestParam;



/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cj
 * @since 2023-04-19
 */
@Slf4j
@Service
public class PersonServiceImpl extends ServiceImpl<PersonMapper, Person> implements PersonService {
@Autowired
private PersonMapper personMapper;

    @Value("${changJiang.shuttleUrl}")
    private String ChangJiangUrl;
    @Value("${oauthUrl.shuttleUrl}")
    private String oauthUrl;
    @Override
    public Result translate(String params) throws Exception {
        //首先解析params里面的参数 然后将这些参数封装到接口里面 然后请求发送最后拿到最后的数据 放到result中返回
        Result result=new Result<>();
        JSONObject jsonObject=JSON.parseObject(params);
        String q="";
        String from="";
        String to="";
        String appid="";
        String salt="";
        String sign="";
        if(jsonObject.containsKey("q")&&jsonObject.get("q")!=null)
        {
            q=jsonObject.getString("q");
        }
        else
        {
            result.setResult("q不合法");
            return  result;
        }
        if(jsonObject.containsKey("from")&&jsonObject.get("from")!=null)
        {
            from=jsonObject.getString("from");
        }
        else
        {
            result.setResult("from不合法");
            return  result;
        }
        if(jsonObject.containsKey("to")&&jsonObject.get("to")!=null)
        {
            to=jsonObject.getString("to");
        }
        else
        {
            result.setResult("to不合法");
            return  result;
        }
        if(jsonObject.containsKey("appid")&&jsonObject.get("appid")!=null)
        {
            appid=jsonObject.getString("appid");
        }
        else
        {
            result.setResult("appid不合法");
            return  result;
        }
        if(jsonObject.containsKey("salt")&&jsonObject.get("salt")!=null)
        {
            salt=jsonObject.getString("salt");
        }
        else
        {
            result.setResult("salt不合法");
            return  result;
        }
        if(jsonObject.containsKey("sign")&&jsonObject.get("sign")!=null)
        {
            sign=jsonObject.getString("sign");
        }
        else
        {
            result.setResult("sign不合法");
            return  result;
        }
        //htp:/api.fanylbaidu.com/api/trans/vip/translate
        URL requestUrl = new URL("http://api.fanyi.baidu.com/api/trans/vip/translate?q="+q+"&from="+from+"&to="+to+"&appid="+appid+"&salt="+salt+"&sign="+sign);
        HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        // 获取响应结果
        StringBuilder response = new StringBuilder();
        try {
            // 先检查是否有输入流
            InputStream inputStream = connection.getInputStream();
            if (inputStream != null) {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                }
            } else {
                // 如果 getInputStream() 返回 null,说明发生了错误
                // 可以在这里设置 response 的结果为 null
                result.setResult(null);
                result.setMessage("未获得任何结果");
                return result;
            }
        } catch (IOException e) {
            // 处理其他 IO 异常
            result.setResult(null);
            result.setMessage("IO 异常: " + e.getMessage());
            return result;
        } catch (Exception e) {
            // 处理其他异常
            result.setResult(null);
            result.setMessage("发生未知异常: " + e.getMessage());
            return result;

        }

// 如果成功获取到响应,解析响应数据
        String responseString = response.toString();
        try {
            // 这里添加解析响应数据的逻辑
            // 例如将 JSON 响应转换为 Java 对象
            Object parsedResult = JSON.parseObject(responseString);
            result.setResult(parsedResult);
            result.setMessage("成功获取结果");
        } catch (Exception e) {
            // 处理解析响应数据时可能出现的异常
            result.setResult(null);
            result.setMessage("解析响应数据时发生异常: " + e.getMessage());
            return result;
        }

        connection.disconnect();

        JSONObject jsonObject1 = JSON.parseObject(response.toString());
        result.setResult(jsonObject1);
        return  result;
    }
    @Override
    public Result add(Person person) throws Exception {
        Result result = new Result();
        //这个变量用来返回所有的错误信息
        String errorMsg="";
        //先查当前是否已经存在这个人了
        LambdaQueryWrapper<Person>personLambdaQueryWrapper=new LambdaQueryWrapper<>();
        personLambdaQueryWrapper.eq(!person.getUserName().equals("")&&person.getUserName()!=null,Person::getUserName,person.getUserName());
//        personLambdaQueryWrapper.eq(!person.getId().equals("")&&person.getId()!=null,Person::getId,person.getId());
        Person person1=personMapper.selectOne(personLambdaQueryWrapper);
        if(person1!=null)
        {
            result.setResult(false);
            result.setMessage("该用户名已经被注册了");
            return result;
        }
        //当不存在的时候根据人名和密码判断是否有
        personLambdaQueryWrapper.eq(!person.getPassword().equals("")&&person.getPassword()!=null,Person::getPassword,person.getPassword());
        personLambdaQueryWrapper.eq(!person.getName().equals("")&&person.getName()!=null,Person::getName,person.getName());
        person1=personMapper.selectOne(personLambdaQueryWrapper);
        if(person1!=null)
        {
            result.setResult(false);
            result.setMessage("已经存在这个人了");
            return result;
        }
         else {
            //这里就是自然而然的插入了
            int rows = personMapper.insert(person);
            System.out.println("这个插入的人是："+person);
            if (rows>0)
            {
                result.setResult(true);
                result.setMessage("插入成功"+errorMsg);
            }
            else
            {
                result.setResult(false);
                result.setMessage("插入失败"+errorMsg);
            }
        }
        return result;
    }

    @Override
    public Result update(String params) throws Exception {
        Result result = new Result<>();
        JSONObject jsonObject = JSON.parseObject(params);
        String id = "";
        String username="";
        if(jsonObject.containsKey("userName"))
        {
            username=jsonObject.getString("userName");
        }
        LambdaQueryWrapper<Person>personLambdaQueryWrapper=new LambdaQueryWrapper<>();
        personLambdaQueryWrapper.eq(Person::getUserName,username);
        Person person=personMapper.selectOne(personLambdaQueryWrapper);
        String password="";
        if(person==null)
        {
            result.setMessage("当前没有查询到这个人");
            return result;
        }
        else
        {
            person=getPersonFromParams(jsonObject);
            person.setUserName(username);
        }
        int t=personMapper.update(person,personLambdaQueryWrapper);
        if(t==1)
        {
            System.out.println("修改成功"+person.getName());
            result.setMessage("修改成功");
        }
        else
        {
            System.out.println("修改失败");
            result.setMessage("修改失败");
        }
        return result;
    }
    public Person getPersonFromParams(JSONObject jsonObject) throws Exception {
        Result result=new Result<>();
        String password="";
        Person person=new Person();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
        //除了用户名对用户的每一个属性进行修改
        if(jsonObject.containsKey("name")&&!jsonObject.getString("name").equals(""))
        {
            if(jsonObject.get("name")!=null)
            person.setName(jsonObject.getString("name"));
        }
        if(jsonObject.containsKey("sex")&&!jsonObject.getString("sex").equals(""))
        {
            if(jsonObject.get("sex")!=null)
            person.setSex(jsonObject.getString("sex"));
        }
        //昵称
//        private String nickname;
        if(jsonObject.containsKey("nickname")&&!jsonObject.getString("nickname").equals(""))
        {
            if(jsonObject.get("nickname")!=null)
            person.setNickname(jsonObject.getString("nickname"));
        }
        //openid
//        private String openid;
        //头像
//        private String avatar;
        if (jsonObject.containsKey("avatar") && !jsonObject.getString("avatar").equals("")) {
            if (jsonObject.get("avatar") != null)
                person.setAvatar(jsonObject.getString("avatar"));
        }

        if(jsonObject.containsKey("password")&&!jsonObject.getString("password").equals(""))
        {
            if(jsonObject.get("password")!=null)
            {
                person.setPassword(jsonObject.getString("password"));
            }
        }
        if(jsonObject.containsKey("tel")&&!jsonObject.getString("tel").equals(""))
        {
            if(jsonObject.get("tel")!=null)
            person.setTel(jsonObject.getString("tel"));
        }
        if(jsonObject.containsKey("birth")&&!jsonObject.getString("birth").equals(""))
        {
            if(jsonObject.get("birth")!=null)
            {
//                System.out.println(ft.parse(jsonObject.getString("birth")));
                LocalDate birthDate = LocalDate.parse(jsonObject.getString("birth"), DateTimeFormatter.ISO_LOCAL_DATE);
//                System.out.println(birthDate);
                person.setBirth(birthDate);
            }
        }
        System.out.println("当前获取到的数据为："+person);
       return person;
    }
    @Override
    public Result login(Person person) throws Exception {
        //        User user = userService.login(userVo);
        Result result=new Result<>();
            LambdaQueryWrapper<Person>personLambdaQueryWrapper=new LambdaQueryWrapper<>();
            personLambdaQueryWrapper.eq(Person::getUserName,person.getUserName());
            Person person1=personMapper.selectOne(personLambdaQueryWrapper);


            if (person1.getPassword().equals(person.getPassword())) {
                result.setResult(true);

            }
            else {
                result.setResult(false);
                 }
            return result;

}
    @Override
    public Result getFromChangJiang(String params) throws Exception {
        Result result=new Result<>();
        log.info("当前向长江提问了,问题是:"+params);
        result.setMessage("已获取数据");
        //解析params包裹成相应的参数
        //写好接口地址
//        这里开始写入post接口并且获取相应的数据
        // 创建URL对象
        URL requestUrl = new URL(ChangJiangUrl);
        HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        try (OutputStream outputStream = connection.getOutputStream();
             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"))) {
            writer.write(params);
            writer.flush();
        }
        // 获取响应结果
        StringBuilder response = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        }
        connection.disconnect();
        log.info("当前从长江拿到的数据为:"+result);
        result.setResult( response.toString());
        log.info("当前从长江拿到的数据为:"+result);
        return result;
    }


}
